package info.maxhis.service;

import info.maxhis.util.DBTool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
/**
 * 短信管理类
 * @author iStar
 *
 */
public class SMSService {
	private DBTool db;
	
	public SMSService(Context context) {
		db = new DBTool(context);
	}
	
	/**
	 * 添加预存短信模板
	 * @param smsBody
	 * @return
	 */
	public boolean addSMS(String smsBody) {
		ContentValues value = new ContentValues();
		value.put("smsBody", smsBody);
		if(db.isClosed()) db.open();
		long count = db.insert("SMS", null, value );
		db.close();
		return (count > 0);
	}
	
	/**
	 * 删除预存短信模板
	 * @param smsId
	 * @return
	 */
	public boolean removeSMS(String smsId){
		if(db.isClosed()) db.open();
		long count = db.delete("SMS", "_id=?", new String[]{smsId});
		db.close();
		return count > 0;
	}
	
	/**
	 * 得到所有预存短信列表
	 * @return
	 */
	public ArrayList<Map<String, String>> getAllSMS(){
		ArrayList<Map<String, String>> list = null;
		if(db.isClosed()) db.open();
		Cursor cursor = db.getAllData("SMS");
		if (cursor != null) {
			list = new ArrayList<Map<String,String>>();
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				Map<String, String> temp = new HashMap<String, String>();
				String smsBody = cursor.getString(cursor.getColumnIndex("smsBody"));
				String id = cursor.getString(cursor.getColumnIndex("_id"));
				temp.put("id", id);
				temp.put("smsBody", smsBody);
				list.add(temp);
			}
		}
		db.close();
		return list;
	}

	/**
	 * 修改
	 * @param sid
	 * @param sms
	 */
	public boolean updateSMS(String sid, String sms) {
		if(db.isClosed()) db.open();
		ContentValues value = new ContentValues();
		value.put("smsBody", sms);
		long count = db.update("SMS", value, "_id=?", new String[]{sid});
		db.close();
		return count > 0;
	}
	
	/**
	 * 根据id得到SMS
	 * @param sid
	 * @return
	 */
	public String getSMSById(String sid){
		String sms = null;
		if(db.isClosed()) db.open();
		Cursor c = db.queryWhere("SMS", "_id=?", new String[]{sid},null);
		if (c != null && c.moveToFirst()) {
			sms = c.getString(c.getColumnIndex("smsBody"));
		}
		db.close();
		return sms;
	}
}
